const BaseIpcHandler = require('../BaseIpcHandler');

class LoadTrainResultsHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log('>> LoadTrainResultsHandler params = ', params);
        const { record_id } = params;

        // 业务逻辑
        let result = null;
        try {
            // 获取训练记录的输出目录
            let records = await this.app.db.train_records.getRecord(record_id);
            if (records.length === 0) {
                result = { code: -1, msg: `Record with ID ${record_id} not found` };
            } else {
                let record = records[0];
                let train_cfg = record.train_cfg;
                // console.log('LoadTrainResults record = ', record);
                let output_dir = record.output_dir;
                let local_model_id = record.local_model_id;

                // 获取模型信息
                let model_locals = await this.app.db.models_local.GetLocalModels(local_model_id);
                let model_local = model_locals[0];
                // console.log(`model_local = `, model_local);

                let model_clouds = await this.app.models_cloud_db.models_cloud.GetCloudModels(model_local.model_id);
                let model_cloud = model_clouds[0];
                // console.log(`model_cloud = `, model_cloud);

                // 获取模型对应的jsproxy路径
                let jsproxy_path = model_cloud.script_jsproxy;
                const handlerClass = require(jsproxy_path);
                const jsproxy = new handlerClass();
                let data = await jsproxy.loadTrainResults(output_dir, train_cfg);
                result = { code: 0, msg: data };
            }
        } catch (err) {
            console.error(`Error get local models: `, err);
            result = { code: -1, msg: err.message };
        }

        // 返回结果
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = LoadTrainResultsHandler;
